package edu.example;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.sql.*;
import java.util.Collection;
import java.util.Iterator;
import java.util.TreeMap;
import java.util.Vector;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;


public class SelectStudentFrame extends JDialog
{
	private JTable studentsTable;
	private JScrollPane scrollPane;
	private JPanel mainPanel;
	private JButton backArrowButton;
	private JButton nextButton;
	private TreeMap<String, Application> data = new TreeMap<String, Application>();
	private Vector<String> attributes = new Vector<String>();
	private Vector<String> dbreader = new Vector<String>();
	private Vector rowData = new Vector();
	private String[][] a2 = null; 
	private String[] columnNames = {"Name","Name","Name",};;
	
	private Application selectedApp;
	private Application selectedAppsubstitite;

	private NextHandler nextHandler;
	private BackHandler backHandler;
	private SelectionListener tableSelectionListener;
	

	
	private UserManager um;
	
	public SelectStudentFrame(UserManager initUm, TreeMap<String, Application> initData)
	{
		this.setTitle("Select Students");
		um = initUm;
		data = initData;
		initData();
		layoutGUI();
	}
	
	public void initData()
	{
		attributes.add(" Name ");
		attributes.add(" Name ");
		attributes.add(" Name ");
		if(!data.isEmpty())
		{
			Collection<Application> temp = data.values();
			Iterator<Application> it = temp.iterator();
			
			int counter = 0;
			

			while(it.hasNext())
			{
				Vector<String> names = new Vector<String>();
				Application tempApp= it.next();
				Application tempApp1= it.next();
				Application tempApp2= it.next();
				
				names.add(tempApp.getApplicantLastName()+" "+tempApp.getApplicantFirstName()+"("+tempApp.getEmailAddress()+")");
				names.add(tempApp1.getApplicantLastName()+" "+tempApp1.getApplicantFirstName()+"("+tempApp1.getEmailAddress()+")");
				names.add(tempApp2.getApplicantLastName()+" "+tempApp2.getApplicantFirstName()+"("+tempApp2.getEmailAddress()+")");

				rowData.add(counter, names);
				counter++;
			}
		}
		else JOptionPane.showMessageDialog(this, 
				"Error: There are no students existing.");
	}
	
	public void layoutGUI()
	{	
		studentsTable = new JTable(rowData,attributes)
		{
			//Disable editing in the table
		    public boolean isCellEditable(int rowIndex, int vColIndex) {return false;}
		};
		studentsTable.setPreferredScrollableViewportSize(new Dimension(720,300));
		studentsTable.setCellSelectionEnabled(true);
		studentsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		
		scrollPane = new JScrollPane(studentsTable);
		mainPanel = new JPanel();
		mainPanel.add(scrollPane);
		this.add(mainPanel);
		
		ImageIcon icon = new ImageIcon("record_back.png");
		backArrowButton = new JButton(icon);
		nextButton = new JButton("Next");
		nextButton.setEnabled(false);
		
		this.setLayout(new GridBagLayout());
		addComponent(backArrowButton,			this,	0,	0,	1,	1);
		addComponent(mainPanel,					this,	1,	1,	1,	1);
		addComponent(nextButton,				this,	2,	2,	1,	1);
		
		Container c = this.getContentPane();
		c.setBackground(Color.WHITE);
		studentsTable.getTableHeader().setBackground(Color.WHITE);
		scrollPane.getViewport().setBackground(Color.WHITE);
		mainPanel.setBackground(Color.WHITE);
		
		// size and locate the dialog at the center of the screen
		this.pack();
		int w = getWidth();
		int h = getHeight();
		Toolkit tk = Toolkit.getDefaultToolkit();
		Dimension screenSize = tk.getScreenSize();
		int screenWidth = screenSize.width;
		int screenHeight = screenSize.height;
		int x = (screenWidth - w)/2;
		int y = (screenHeight - h)/2;
		setLocation(x,y);
	
		nextHandler = new NextHandler();
		backHandler = new BackHandler();
		tableSelectionListener = new SelectionListener();
		
		backArrowButton.addActionListener(backHandler);
		nextButton.addActionListener(nextHandler);
		
		studentsTable.addMouseListener(tableSelectionListener);
	}
	
	// method helping GridBagLayout
	public void addComponent(	JComponent jc, Container c, 
			int x, int y, int w, int h){
		GridBagConstraints gbc = new GridBagConstraints();
		gbc.gridx = x;
		gbc.gridy = y;
		gbc.gridwidth = w;
		gbc.gridheight = h;
		gbc.fill = GridBagConstraints.HORIZONTAL;
		gbc.insets = new Insets(5, 5, 5, 5);
		c.add(jc, gbc);
	}
	
	public static void main(String[] args)
	{
		File file1 = new File("AY(New).txt");
		File file2 = new File("AY-map.txt");
		File file3 = new File("OTS.txt");
		File file4 = new File("OTS-map.txt");
		ApplicationManagerCloud formatter = new ApplicationManagerCloud(null, file1, file2, file3, file4);
		UserManager um = new UserManager();
		um.login("chair", "abc");
		SelectStudentFrame temp = new SelectStudentFrame(um, formatter.getAllApps());
		temp.setVisible(true);
	}
	
	class SelectionListener implements MouseListener
	{
		public void mouseClicked(MouseEvent e) 
		{
			int row = studentsTable.getSelectedRow();
			int col = studentsTable.getSelectedColumn();
			String temp = (String)studentsTable.getValueAt(row, col);
			int beginIndex = temp.indexOf("(");
			int endIndex = temp.indexOf(")");
			String email = temp.substring(beginIndex+1, endIndex);
			
			/*try { 
				Connection conn=ConnectionUtils.getConnection();
	            if(!conn.isClosed()) 
	             System.out.println("Succeeded connecting to the Database!");

                PreparedStatement pstmt = conn.prepareStatement("select * from aydata where email_address = ?",
                        ResultSet.TYPE_SCROLL_SENSITIVE,
                          ResultSet.CONCUR_UPDATABLE);
                pstmt.setString(1, email);
                ResultSet rs = pstmt.executeQuery();
	            String reader = null;
                int column=1;
	            if(rs.next()) {
	            	while(column<81){
	            	reader = rs.getString(column);
	            	reader = new String(reader.getBytes("ISO-8859-1"),"GB2312");
	            	System.out.println(reader);
	                dbreader.addElement(reader);
	                column++;
	            	}
	            }
	            for(int i=0;i<80;i++)
	            	System.out.println(dbreader.get(i));
	            
	            rs.close();
	            conn.close();
	           } catch(Exception e1) {	             
	            e1.printStackTrace();
	           }*/
	            
			
			selectedApp = data.get(email);
			if(selectedApp != null)
			{
				nextButton.setEnabled(true);
			}
		}

		public void mousePressed(MouseEvent e) {}
		public void mouseReleased(MouseEvent e) {}
		public void mouseEntered(MouseEvent e) {}
		public void mouseExited(MouseEvent e) {}
		
	}
	
	class NextHandler implements ActionListener
	{
		public void actionPerformed(ActionEvent e) 
		{
			ApplicationManagerCloud ap = ApplicationManagerCloud.getAppManager();
			if(ap.getAllScore().containsKey(selectedApp.getEmailAddress()))
			{
				viewAppFrame temp = new viewAppFrame(selectedApp, ap.getAllScore().get(selectedApp.getEmailAddress()),um);
				temp.setVisible(true);
			}
			else
			{
				viewAppFrame temp = new viewAppFrame(selectedApp, null,um);
				temp.setVisible(true);
			}
			SelectStudentFrame.this.setVisible(false);
		}
		
	}
	class BackHandler implements ActionListener
	{
		public void actionPerformed(ActionEvent e) 
		{
			SelectStudentFrame.this.setVisible(false);
		}
	}

}
